<?php

namespace App\Jobs\Publish;

use App\Models\Operation\ContentTemplateDetails;
use App\Models\Operation\TemplateAreaData;
use App\Models\Operation\TemplateSubcolumnVassetiData;
use DB;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ContentTemplateJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 任务最大尝试次数
     *
     * @var int
     */
    public $tries = 1;

    /**
     * 任务运行的超时时间。
     *
     * @var int
     */
    public $timeout = 3600;
    protected $publishContentTemplateHistory;
    // 模板类型
    public $template_type;
    // 模板编号
    public $template_no;
    // 当前模板详情列表的ID
    public $template_details_id;
    // 当前模板的类型ID
    public $content_template_id;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($publishContentTemplateHistory, $template_type, $template_no, $template_details_id,$content_template_id)
    {
        $this->publishContentTemplateHistory = $publishContentTemplateHistory;
        $this->template_type                 = $template_type;
        $this->template_no                   = $template_no;
        $this->template_details_id           = $template_details_id;
        $this->content_template_id           = $content_template_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
      //dd($this->publishContentTemplateHistory);
	 $history = [];
        // 总行数
        $rowsCount = 0;
        // 导入开始时间
        $starttime = microtime(true);
        // 开始使用内存
        $startMemory = memory_get_usage();
        // 批次自动生成
        $batch = date('YmdHis');
        $datas = [];
        // 准备区位图片数据
        $imgDatas       = self::getTemplateAreaImg($this->template_type, $this->template_no, $this->template_details_id);
        // 准备模板数据
        $datas          = $this->getTemplateAreaData($this->template_type, $this->template_no, $this->template_details_id);
        // 准备二级栏目媒资数据
        $subcolumnDatas = self::getSubcolumnVassetiData($this->template_details_id);
        // 开启事务
        DB::connection('interface')->beginTransaction();
        try {
            // 删除对应模板数据
            self::deleteTemplateAreaData($this->template_type, $this->template_no);
            // 删除二级媒资数据
            self::deleteSubcolumnVassetiData();
            // 删除接口图片数据
            self::deleteTemplateAreaImg($this->template_type, $this->template_no);
            // 更新当前模板状态为已发布,其他模板下线
            self::updatePublishStatus($this->content_template_id,$this->template_details_id);
            // 新增数据
            DB::connection('interface')->table('template_area_datas')->insert($datas);
            DB::connection('interface')->table('template_subcolumn_vasseti_datas')->insert($subcolumnDatas);
            DB::connection('interface')->table('template_area_images')->insert($imgDatas);
            DB::connection('interface')->commit();
        } catch (\Exception $e) {
            //事务回滚
            DB::connection('interface')->rollback();
            dd($e->getMessage());
        }
        // 总记录数
        $num              = count($datas);
        $rowsCount        = $num;
        $history['count'] = $num;
        $datas            = [];

        // 结束时间
        $endtime        = microtime(true);
        $consuming_time = round($endtime - $starttime, 4);
        $endMemory      = memory_get_usage();
        $usedMemory     = ($endMemory - $startMemory) / 1024;

        $flag    = true;
        $message = '<div style="word-wrap: break-word;">';
        $message .= '耗时:';
        $message .= $consuming_time . '秒<br />';
        $message .= '耗费内存:';
        $message .= "{$usedMemory} K<br />";

        $message .= '数据总数:';
        $message .= $history['count'] . '行<br />';
        $message .= '成功的行数:';
        $message .= $num . '行<br />';

        $message .= '</div>';

        if ($flag) {
            $message = '<div class="alert alert-success">' . $message . '</div>';
        } else {
            $message = '<div class="alert alert-error">' . $message . '</div>';
        }

        $this->publishContentTemplateHistory->success_count  = $num;
        $this->publishContentTemplateHistory->consuming_time = $consuming_time;
        $this->publishContentTemplateHistory->used_memory    = $usedMemory;
        $this->publishContentTemplateHistory->content        = $message;
        $this->publishContentTemplateHistory->save();
    }

    /**
     * 区位模板数据
     */
    public function getTemplateAreaData($template_type, $template_no, $template_details_id)
    {
        // 每一条模板数据
        $data             = [];
        $datas            = [];
        $templateAreaData = TemplateAreaData::whereNotNull('template_details_id')->where(['template_details_id' => $template_details_id, 'template_type' => $template_type, 'template_no' => $template_no])->get();
        foreach ($templateAreaData as $key => $value) {
            $this->publishContentTemplateHistory->increment('done_count');
            // $this->publishContentTemplateHistory->update([
            //     'done_count' => DB::raw("done_count + 1"),
            // ]);
            // 模板类型
            $data['template_type'] = $value->template_type;
            // 模板编号, 例子:001
            $data['template_no'] = $value->template_no;
            // 资源类型, 1 => 直播, 2 => 专题，3 => 推荐位，4=>点播媒资 5=>栏目列表
            $data['resource_type'] = $value->resource_type;
            // 区位编号, 例如: AREA001x1x0y0
            $data['area_no'] = $value->area_no;
            // 具体到某一个位置的编号
            $data['tag_no'] = $value->tag_no;
            // 区位文件资源ID
            $data['resource_id'] = $value->resource_id;
            // 开始时间
            $data['start_time'] = $value->start_time;
            // 结束时间
            $data['end_time'] = $value->end_time;
            // 首页类型 1-首页 2-直播首页 3-点播首页 4回看首页
            $data['home_type'] = $value->home_type;
            // 栏目列表ID
            $data['collist_id'] = $value->collist_id;
            // 栏目ID
            $data['column_id'] = $value->column_id;
            // 二级栏目ID
            $data['subcolumn_id'] = $value->subcolumn_id;
            $datas[]              = $data;
        }
        return $datas;
    }

    /**
     * 获取区位图片信息
     */
    public static function getTemplateAreaImg($template_type, $template_no, $template_details_id)
    {
        // 获取全部的图片
        $imgs = [];
        // 获取图片区位信息
        $img              = [];
        $templateAreaImgs = DB::table('template_area_images')
            ->where(['template_type' => $template_type, 'template_no' => $template_no, 'template_details_id' => $template_details_id])
            ->whereNull('deleted_at')
            ->get();
        // return $templateAreaImgs;
        foreach ($templateAreaImgs as $key => $value) {
            $img['template_type'] = $value->template_type;
            $img['template_no']   = $value->template_no;
            $img['area_no']       = $value->area_no;
            $img['tag_no']        = $value->tag_no;
            $img['subcolumn_id']  = $value->subcolumn_id;
            $img['img']           = $value->img;
            $imgs[]               = $img;
        }
        return $imgs;
    }
    /**
     * 二级栏目媒资
     */
    public static function getSubcolumnVassetiData($template_details_id)
    {
        // 每一条模板005的二级栏目
        $subcolumn = [];
        // 存放模板005的某一个二级栏目下的所有媒资
        $subcolumns = [];
        // 获取所有栏目数据
        $subColumnVatssetis = TemplateSubcolumnVassetiData::whereNotNull('template_details_id')->where(['template_details_id' => $template_details_id])->get();
        foreach ($subColumnVatssetis as $key => $value) {
            // 查询对应二级栏目下的媒资
            $subcolumn['subcolumn_id'] = $value->subcolumn_id;
            $subcolumn['area_no']      = $value->area_no;
            $subcolumn['vasseti_id']   = $value->vasseti_id;
            $subcolumn['type']         = $value->type;
            $subcolumns[]              = $subcolumn;
        }
        return $subcolumns;
    }
    /*
     * 更新区位模板历史记录
     */
    public function updatePublishHistory()
    {
        try {
            $this->publishContentTemplateHistory->update([
                'done_count' => DB::raw("done_count + 1"),
            ]);
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }

    /**
     * 删除模板数据
     */
    public static function deleteTemplateAreaData($template_type, $template_no)
    {
        try {
            return DB::connection('interface')->table('template_area_datas')->where(['template_type' => $template_type, 'template_no' => $template_no])->delete();
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }

    /**
     * 删除二级栏目媒资数据
     */
    public static function deleteSubcolumnVassetiData()
    {
        try {
            return DB::connection('interface')->table('template_subcolumn_vasseti_datas')->delete();
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }

    /**
     * 清空接口区位图片信息表
     */
    public static function deleteTemplateAreaImg($template_type, $template_no)
    {
        try {
            return DB::connection('interface')->table('template_area_images')->where(['template_type' => $template_type, 'template_no' => $template_no])->delete();
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }
    /**
     * 更新发布状态
     */
    public static function updatePublishStatus($content_template_id,$template_details_id)
    {
        try {
            // 更新已上线的发布状态为下线,已发布
            $contentTemplate = ContentTemplateDetails::onlineStatus()
                ->onlinePublished()
                ->where('content_template_id','=',$content_template_id)
                ->where('id', '<>', $template_details_id)
                ->update(['online_status' => 0, 'publish_status' => 0, 'publish_down_status' => 1, 'offline_at' => date('Y-m-d H:i:s')]);

            return DB::table('content_template_details')->where(['id' => $template_details_id])->update(['publish_status' => 1]);
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }
}
